package cc.common.base;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<T> {
    private Disposable disposable;
    private LifecycleOwner mOwner;

    public BaseObserver(LifecycleOwner owner) {
        this.mOwner = owner;
        owner.getLifecycle().addObserver(new LifecycleObserver() {
            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            void onDestroy() {
                disposable.dispose();
                owner.getLifecycle().removeObserver(this);
                mOwner = null;
            }
        });
    }

    public BaseObserver() {

    }

    @Override
    public void onSubscribe(Disposable d) {
        disposable = d;
    }

    @Override
    public void onNext(Object o) {
        doNext((T) o);
    }

    protected abstract void doNext(T t);

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
}
